package com.gutou.yeaicodemother.aop;

import com.gutou.yeaicodemother.annotation.AuthCheck;
import com.gutou.yeaicodemother.model.enums.UserRoleEnum;
import com.gutou.yeaicodemother.exception.ErrorCode;
import com.gutou.yeaicodemother.exception.ThrowUtils;
import com.gutou.yeaicodemother.model.entity.User;
import com.gutou.yeaicodemother.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 从注解中获取必须的角色
        String mustRole = authCheck.mustRole();
        // 获取当前登录用户信息
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        User user = userService.getLoginUser(request);
        // 从注解中获取必须的角色枚举
        UserRoleEnum mustRoleEnum = UserRoleEnum.getByValue(mustRole);
        // 不需要权限，放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 以下为需要权限的情况
        // 获取当前用户拥有的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getByValue(user.getUserRole());
        // 没有权限，抛出异常
        ThrowUtils.throwIf(userRoleEnum == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(UserRoleEnum.ADMIN.equals(mustRoleEnum) &&
                !UserRoleEnum.ADMIN.equals(userRoleEnum),ErrorCode.NO_AUTH_ERROR);
        // 有权限，放行
        return joinPoint.proceed();
    }
}
